package com.yq.practice.tree;

import java.util.ArrayList;
import java.util.Collections;

/**
 * @ClassName HuffmanTreePractice
 * @Description TODO
 * @Author yaoqiang
 * @Date 2021/11/17 11:38
 * @Version 1.0
 */
public class HuffmanTreePractice {
    public static void main(String[] args) {
        int[] arr = {7, 5, 2, 4};
        Node node = createHuffmanTree(arr);
        preOrder(node);
    }

    private static void preOrder(Node node) {
        if (node != null) {
            node.preOrder();
        }
    }

    private static Node createHuffmanTree(int[] arr) {
        ArrayList<Node> nodes = new ArrayList<Node>();
        for (int value : arr) {
            nodes.add(new Node(value));
        }
        while (nodes.size() > 1) {
            Collections.sort(nodes);
            Node left = nodes.get(0);
            Node right = nodes.get(1);
            Node parent = new Node(left.value + right.value);
            parent.left = left;
            parent.right = right;
            nodes.remove(left);
            nodes.remove(right);
            nodes.add(parent);
        }
        return nodes.get(0);
    }
}

class Node implements Comparable<Node> {
    int value;
    Node left;
    Node right;

    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    @Override
    public int compareTo(Node o) {
        return this.value - o.value;
    }

    public void preOrder() {
        System.out.println(this.value);
        if (this.left != null) {
            this.left.preOrder();
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }
}
